package com.qk.management.service.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.RoleException;
import com.qk.dto.role.RoleDTO;
import com.qk.entity.Role;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 上官徵羽
 * @version 1.0
 * @since 2025-10-08 7:21
 */
@Service
@SuppressWarnings("all")
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public PageResult<Role> listPage(RoleDTO roleDTO) {
        PageHelper.startPage(roleDTO.getPage(), roleDTO.getPageSize());
        List<Role> listPage = roleMapper.listPage(roleDTO);
        Page<Role> role = (Page<Role>)listPage;
        return PageResult.<Role>builder()
                .total(Long.parseLong(role.getTotal() + ""))
                .rows(listPage)
                .build();
    }

    @Override
    public void deleteById(Integer id) {
        roleMapper.deleteById(id);
    }

    @Override
    public void addRole(Role role) {
        judgeRepetition(role.getName(), null);
        LocalDateTime now = LocalDateTime.now();
        role.setCreateTime(now);
        role.setUpdateTime(now);
        roleMapper.addRole(role);
    }

    @Override
    public Role getById(Integer id) {
        return roleMapper.getRoleById(id);
    }

    @Override
    public void updateRole(Role role) {
        judgeRepetition(role.getName(), role.getId());
        LocalDateTime now = LocalDateTime.now();
        role.setUpdateTime(now);
        roleMapper.update(role);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.listAll();
    }

    public void judgeRepetition(String name,Integer id){
        Role role = roleMapper.getByName(name);
        if (!ObjectUtil.equals(id, role.getId())&&!ObjectUtil.isEmpty(role)){
            RoleException.throwRoleException(ParamEnum.ROLE_NAME_ALREADY_EXISTS);
        }
    }
}
